package com.boyinet.imesh2json.common;


import de.felixroske.jfxsupport.AbstractFxmlView;
import de.felixroske.jfxsupport.FXMLView;
import de.felixroske.jfxsupport.GUIState;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
public class UiUtil implements ApplicationContextAware {

    // Spring应用上下文环境
    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的回调方法。设置上下文环境
     *
     * @param applicationContext spring context
     */
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) {
        if (UiUtil.applicationContext == null) {
            UiUtil.applicationContext = applicationContext;
        }
    }

    /**
     * 显示窗口
     */
    public static void showModal(final Class<? extends AbstractFxmlView> window, final Modality mode, String title) {
        final AbstractFxmlView view = applicationContext.getBean(window);
        FXMLView annotation = window.getAnnotation(FXMLView.class);

        Stage newStage = new Stage();

        Scene newScene;
        if (view.getView().getScene() != null) {
            // This view was already shown so
            // we have a scene for it and use this one.
            newScene = view.getView().getScene();
        } else {
            newScene = new Scene(view.getView());
        }

        newStage.setScene(newScene);
        newStage.initModality(mode);
        newStage.initOwner(GUIState.getStage());
        title = title == null ? annotation.title() : title;
        newStage.setTitle(title);
        newStage.initStyle(StageStyle.valueOf(annotation.stageStyle().toUpperCase(Locale.ROOT)));

        newStage.showAndWait();
    }
}

